package com.timoon.component.panel.jqgrid.action;

import org.apache.wicket.AttributeModifier;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.form.Form;

import com.googlecode.wicket.jquery.ui.form.button.AjaxButton;
import com.timoon.app.utils.HttpServletUtil;
import com.timoon.component.panel.jqgrid.JqGridPanel;

/**
 * 此button配合jqGrid使用
 * 点击此button会激发事件，获取jqgrid用户选中的记录id(只有一个)<br>
 * 并发送到controller，controller会将值赋予到mainpanel.detailsId<br>
 * 此button的onSubmit()会等待发现mainPanel.detailsId的存在,约定detailsId="-1"为客户端验证失败<br>
 * 一旦发现值后取出，并置空，以免对下次造成勿扰
 * @author Administrator
 *
 */
public abstract class RecordIdsReceiverAjaxButton extends AjaxButton {

	private String gridKey;
	private JqGridPanel mainPanel;
	
	public RecordIdsReceiverAjaxButton(String id,JqGridPanel mainPanel) {
		super(id);
		// TODO Auto-generated constructor stub
		
		this.gridKey=mainPanel.getKey();
		this.mainPanel=mainPanel;
		
		this.add(new AttributeModifier("onclick","myjqgrid.sendDeatilsId('"+gridKey+"','"+HttpServletUtil.getBasePath()+"');"));
	}
	
	@Override
	protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
		// TODO Auto-generated method stub
		super.onSubmit(target, form);
		
		String detailsId=mainPanel.getDetailsId();

		while(detailsId==null){
			try {
				Thread.sleep(500);
				detailsId=mainPanel.getDetailsId();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		if(!detailsId.equals("-1")){
			this.onReceivedRecordId(detailsId,target);
		}
		
		mainPanel.setDetailsId(null);
		
	}
	protected abstract void onReceivedRecordId(String recordId,AjaxRequestTarget target);

}
